import { isUndefined, isNull, getTSFromPb } from "mmb";
import * as activity_user_pv_logpb from "../grpc-client/service/activity_user_pv_log_pb";
import {
  getBgsActivityUserPvLogOpSafely,
  getMetadata,
  getOptionsOfLight,
  wrapperGrpcError,
} from "../grpc-client/grpcAdapter";
import { CreateActivityUserPvLogParams } from "./declareTypes";
import { getPub, makeTopicOfPub, wrapToMessage } from "../proxy/nsqProxy";

/****************************************************************************************/
/*                                   activity_user_pv_log entity                                 */
/****************************************************************************************/
const topicOfAddActivityUserPvLog = "add-activity_user_pv_log";

/****************************************************************************************/
/*                                   activity_user_pv_log cmd                           */
/****************************************************************************************/

export const createActivityUserPvLogMq = async ({
  userId,
  activityId,
  shareUserId,
  page,
}: CreateActivityUserPvLogParams): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    const topic = makeTopicOfPub(topicOfAddActivityUserPvLog)
    const msg = wrapToMessage({
      userId: Number(userId),
      activityId: Number(activityId),
      shareUserId: Number(shareUserId),
      page,
    })
    // console.log('publish createActivityUserPvLogMq =>', topic ,JSON.stringify(msg))
    getPub().publish(
      topic,
      msg,
      (err) => {
        if (err) {
          // console.log("createActivityUserPvLogMq err", err);
          reject(false);
        }
        // console.log("createActivityUserPvLogMq success");
        resolve(true);
      }
    );
  });
};

/****************************************************************************************/
/*                                   activity_user_pv_log query                         */
/****************************************************************************************/

/****************************************************************************************/
/*                                   activity_user_pv_log aggs query                    */
/****************************************************************************************/

export interface AggsToActivityUserPvCount {
  activityId: string;
  viewCount: number;
}

const aggsToActivityUserPvCountPbToObject = (
  pb: activity_user_pv_logpb.AggsToActivityUserPvCountEntity
): AggsToActivityUserPvCount => {
  return {
    activityId: `${pb.getActivityId()}`,
    viewCount: pb.getViewCount(),
  };
};

export const listAggsToActivityUserPvCounts = async (
  activityIds: string[]
): Promise<AggsToActivityUserPvCount[]> => {
  const cl = getBgsActivityUserPvLogOpSafely();
  const req = new activity_user_pv_logpb.ListAggsToActivityUserPvCountByActivityIDsRequest();

  req.setActivityIdsList(activityIds.map(Number));

  return new Promise((resolve, reject) => {
    cl.listAggsToActivityUserPvCountByActivityIDs(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }

        resolve(
          res
            .getAggsToActivityUserPvCountsList()
            .map(aggsToActivityUserPvCountPbToObject)
        );
      }
    );
  });
};
